package com.tuanzi.loan.web.bean.family;

import com.tuanzi.loan.business.service.family.UpdateVersionService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.view.family.UpdateVersionView;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

@Data
@Debug
@Slf4j
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class UpdateVersionInfoBean extends JSFInfoBean<UpdateVersionView> {

    private static final long serialVersionUID = 7991360430728821488L;

    @Autowired
    private UpdateVersionService updateVersionService;

    @PostConstruct
    private void init() {
        String id = getParamFromRequest("id");
        if (StringUtils.isNotBlank(id)) {
            $ = updateVersionService.findById(Integer.valueOf(id));
        } else {
            $ = new UpdateVersionView();
            changeStatusToAdd();
        }
    }

    public void onSave() {
        if (!validation()) {
            return;
        }
        $ = updateVersionService.save($);
        changeStatusToView();
        addSuccessfullyMessage();
    }

    public boolean validation() {
        if (StringUtils.isBlank($.getVersionNo())) {
            addErrorMessage("版本序号不能为空");
            return false;
        }

        if ($.getUpdateType() == null) {
            addErrorMessage("更新类型不能为空");
            return false;
        }

        if (CollectionUtils.isEmpty($.getPrdIds())) {
            addErrorMessage("产品id不能为空");
            return false;
        }

        if ($.getIsCornerIconShow() == null) {
            addErrorMessage("左上角人头icon是否显示不能为空");
            return false;
        }

        if (StringUtils.isBlank($.getContent())) {
            addErrorMessage("文案不能为空");
            return false;
        }

        return true;
    }

    @Override
    public void changeStatusToView() {
        if (null != $.getId()) {
            $ = updateVersionService.findById($.getId());
        } else {
            $ = new UpdateVersionView();
        }
        super.changeStatusToView();
    }
}
